package com.shujia.flink.tf

import org.apache.flink.api.java.functions.KeySelector
import org.apache.flink.streaming.api.scala._

object Demo5KeyBy {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    val linesDS: DataStream[String] = env.socketTextStream("master", 8888)

    val kvDS: DataStream[(String, Int)] = linesDS
      .flatMap(_.split(","))
      .map((_, 1))

    /**
     * keyBy ：将相同的key发送到同一个task中
     */
    //scala api
    val scalaDS: KeyedStream[(String, Int), String] = kvDS.keyBy((kv: (String, Int)) => kv._1)

    //scalaDS.print()

    //java api
    val javaDS: KeyedStream[(String, Int), String] = kvDS.keyBy(new KeySelector[(String, Int), String] {
      /**
       * getKey： 返沪key
       *
       * @param kv ： 一行数据
       * @return
       */
      override def getKey(kv: (String, Int)): String = {
        kv._1
      }
    })
    javaDS.print()

    env.execute()
  }

}
